//初始化验证码
// var verifyCode = new GVerify({
//   id: "verify-img", //容器的ID
//   type: "number", //图形验证码的类型：blend-数字字母混合类型（默认）、number-纯数字、letter-纯字母
// });
// //刷新验证码
// verifyCode.refresh();
// //校验验证码
// let verifyVal = verifyCode.validate("校验的值");

const form = document.querySelector("form");
const phone = document.querySelector("[name=phone]");
const phoneReg = /^(?:(?:\+|00)86)?1\d{10}$/;
const txyzm = document.querySelector("[name=txyzm]");
let txyzmVal = "";
const yzmReg = /^\d+$/;
const dxyzm = document.querySelector("[name=dxyzm]");
let dxyamVal = "";
const verifVal = document.querySelector("#verifyImg");
const oImg = document.querySelector("#verifyImg img");
let verifUrl = "";
let verifKey = "";
const getCode = document.querySelector("#getCode");
let codeIndex = 0;
let phoneVal = "";

//界面加载获取图形验证码
function getTxCode() {
  axios
    .get("http://cba.itlike.com/public/index.php?s=/api/captcha/image")
    .then(({ data: { data } }) => {
      verifKey = data.key;
      oImg.src = data.base64;
    });
}
getTxCode();

//界面加载若本地存储有手机号则赋值给输入框
const phoneUser = JSON.parse(localStorage.getItem("userMsg")) || [];

if (phoneUser.userPhone.length > 0) {
  phone.value = phoneUser.userPhone;
}
  //点击刷新图形验证码
  verifVal.addEventListener("click", function () {
    getTxCode();
  });

getCode.addEventListener("click", function () {
  phoneVal = phone.value;
  if (!phoneVal) {
    return alert("请输入手机号！");
  }
  getCodeFn();
  txyzmVal = txyzm.value;
  getPhoneCode(txyzmVal, verifKey, phoneVal);
});

function getCodeFn() {
  let flag = false;
  let timer = null;
  let index = 5;
  if (!flag) {
    timer = setInterval(function () {
      index--;
      if (index <= 0) {
        getCode.innerHTML = "点击再次再获取";
        clearInterval(timer);
        flag = false;
        return;
      }
      getCode.innerHTML = `${index}秒后再获取`;
    }, 1000);
  }
}

//获取短信验证码
function getPhoneCode(captchaCode, captchaKey, mobile) {
  axios
    .post(
      "http://cba.itlike.com/public/index.php?s=/api/captcha/sendSmsCaptcha",
      {
        form: { captchaCode, captchaKey, mobile },
      }
    )
    .then((res) => {
      console.log(res);
      console.log(res.data.message);
    })
}

form.addEventListener("submit", function (e) {
  e.preventDefault();
  phoneVal = phone.value;
  if (!phoneReg.test(phoneVal)) {
    phone.focus();
    phone.value = "";
    return alert("手机号格式不正确~");
  }
  if (dxyzm.value.trim().length < 1) {
    return alert("请输入手机验证码");
  }
  console.log(dxyzm.value, phoneVal);
  axios
    .post("passport/login", {
      form: {
        smsCode: dxyzm.value,
        mobile: phoneVal,
        isParty: false,
        partyData: {},
      },
    })
    .then(({ data }) => {
      let user = {
        token: data.data.token,
        userPhone: phoneVal
      }
      alert("恭喜你，登录成功~");
      location.href = "mine/mine.html";
      localStorage.setItem("userMsg", JSON.stringify(user));
    });
});
